package sdk.pay.utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import sdk.pay.constant.PayConstant;

/**
 * Created by Joe on 2017/6/14 0014 09:08.
 * get current location
 */

public class PayLocationUtil {
    private static final String url = "http://pv.sohu.com/cityjson?/";

    /**
     * get city name by net api
     */
    public void getCityNameByApi(final CityNameCallBack callBack) {
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder().connectTimeout(PayConstant.TIME_OUT,
                TimeUnit.SECONDS).readTimeout(PayConstant.TIME_OUT, TimeUnit.SECONDS).build();
        mOkHttpClient.newCall(new Request.Builder().url(url).build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                PayLogUtil.logFourth("PayLocationUtil getCityName onFailure IOException = " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.body()) {
                    String result = response.body().string();
                    if (response.isSuccessful()) {
                        try {
                            int first = result.indexOf("{");
                            int end = result.lastIndexOf("}");
                            if (-1 != first && -1 != end) {
                                JSONObject jsonObject = new JSONObject(result.substring(first, (end + 1)));
                                PayLogUtil.logFourth(jsonObject.toString());
                                if (callBack != null) {
                                    callBack.transferCName(jsonObject.getString("cname"));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            PayLogUtil.logFourth("PayLocationUtil getCityName onResponse jsonObject error");
                        }
                    } else {
                        PayLogUtil.logFourth("PayLocationUtil getCityName onResponse failure");
                    }
                } else {
                    PayLogUtil.logFourth("PayLocationUtil getCityName response body = null");
                }
            }
        });
    }

    public interface CityNameCallBack {
        void transferCName(String cName);
    }
}
